import pygame
import random
import os

# 初始化Pygame
pygame.init()

# 游戏窗口设置
SCREEN_WIDTH = 480
SCREEN_HEIGHT = 720
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("羊了个羊")

# 颜色定义
BG_COLOR = (255, 255, 255)
BUTTON_COLOR = (200, 200, 200)  # 清除按钮颜色
TEXT_COLOR = (0, 0, 0)  # 按钮文字颜色

# 卡片尺寸和间距
CARD_WIDTH = 55
CARD_HEIGHT = 70
SPACING = 7
GROUP_SPACING = 20  # 每组卡片中间的间隔

# 游戏区域布局
GRID_ROWS = 4
GRID_COLS = 4
grid_width = GRID_COLS * (CARD_WIDTH + SPACING) + (GRID_COLS - 1) * GROUP_SPACING
GRID_LEFT = (SCREEN_WIDTH - grid_width) // 2
GRID_TOP = 200  # 向下偏移

# 槽位区域设置
SLOT_ROWS = 1
SLOT_COLS = 7  # 最多存放7个卡片
slot_width = SLOT_COLS * (CARD_WIDTH + 5) - 5
SLOT_LEFT = (SCREEN_WIDTH - slot_width) // 2
SLOT_TOP = SCREEN_HEIGHT - CARD_HEIGHT - 50
SLOT_HEIGHT = CARD_HEIGHT + 20

# 清除按钮设置
BUTTON_WIDTH = 80
BUTTON_HEIGHT = 40
BUTTON_LEFT = SCREEN_WIDTH - BUTTON_WIDTH - 20
BUTTON_TOP = 60  # 这里将按钮向下调整，原来为20，现在改为60，你可以根据需要调整这个值

# 加载图片
try:
    image_folder = os.path.join(os.path.dirname(__file__), "image")
    background_path = os.path.join(image_folder, "back.png")
    background_img = pygame.image.load(background_path)
    background_img = pygame.transform.scale(background_img, (SCREEN_WIDTH, SCREEN_HEIGHT))
    print("主背景图像加载成功")
except Exception as e:
    print(f"主背景图像加载失败: {e}")
    background_img = None

# 加载槽位背景图像
try:
    slot_bg_path = os.path.join(image_folder, "back2.png")
    slot_bg_img = pygame.image.load(slot_bg_path)
    slot_bg_img = pygame.transform.scale(slot_bg_img, (slot_width + 20, SLOT_HEIGHT + 20))
    print("槽位背景图像加载成功")
except Exception as e:
    print(f"槽位背景图像加载失败: {e}")
    slot_bg_img = None

card_images = []
try:
    for i in range(5):
        if i == 0:
            tile_path = os.path.join(image_folder, "tile.png")
        else:
            tile_path = os.path.join(image_folder, f"tile{i}.png")

        if os.path.exists(tile_path):
            img = pygame.image.load(tile_path)
            img = pygame.transform.scale(img, (CARD_WIDTH, CARD_HEIGHT))
            card_images.append(img)
            print(f"卡片图片 {os.path.basename(tile_path)} 加载成功")
        else:
            print(f"卡片图片 {tile_path} 不存在")

    if not card_images:
        raise Exception("没有找到任何卡片图片")

except Exception as e:
    print(f"卡片图片加载失败: {e}")
    COLORS = [
        (255, 0, 0),
        (255, 255, 0),
        (0, 255, 0),
        (0, 0, 255),
        (128, 0, 128)
    ]

# 游戏状态
slots = []
score = 0
game_over = False
game_won = False
button_uses = 3  # 清除按钮使用次数
moving_card = None  # 正在移动的卡片
start_pos = (0, 0)  # 起始位置
end_pos = (0, 0)  # 目标位置
step = 5  # 每次移动的步数


# 检查是否胜利
def check_victory():
    for row in grid:
        for stack in row:
            if len(stack) > 0:
                return False
    return len(slots) == 0


# 初始化卡片堆
grid = []
for row in range(GRID_ROWS):
    grid_row = []
    for col in range(GRID_COLS):
        layers = random.randint(3, 5)
        max_card_type = len(card_images) - 1 if card_images else len(COLORS) - 1
        stack = [random.randint(0, max_card_type) for _ in range(layers)]
        stack += [stack[-1]] * (3 - layers % 3) if layers % 3 != 0 else []
        grid_row.append(stack)
    grid.append(grid_row)

# 主循环
clock = pygame.time.Clock()
running = True

while running:
    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN and not game_over:
            mouse_x, mouse_y = pygame.mouse.get_pos()
            clicked_row = None
            clicked_col = None

            # 检查是否点击了清除按钮
            if BUTTON_LEFT <= mouse_x < BUTTON_LEFT + BUTTON_WIDTH and \
                    BUTTON_TOP <= mouse_y < BUTTON_TOP + BUTTON_HEIGHT and \
                    button_uses > 0:
                slots = []
                button_uses -= 1

            else:
                # 遍历卡片堆寻找被点击的顶层卡片
                for row in range(GRID_ROWS):
                    for col in range(GRID_COLS):
                        stack = grid[row][col]
                        if not stack:
                            continue
                        # 计算顶层卡片实际位置
                        base_x = GRID_LEFT + col * (CARD_WIDTH + SPACING + GROUP_SPACING)
                        base_y = GRID_TOP + row * (CARD_HEIGHT + SPACING)

                        # 碰撞检测
                        if (base_x <= mouse_x < base_x + CARD_WIDTH and
                                base_y <= mouse_y < base_y + CARD_HEIGHT):
                            clicked_row, clicked_col = row, col
                            break
                    if clicked_row is not None:
                        break

                if clicked_row is not None and clicked_col is not None:
                    if len(grid[clicked_row][clicked_col]) > 0:
                        if len(slots) >= SLOT_COLS:
                            game_over = True
                            continue

                        moving_card = grid[clicked_row][clicked_col].pop()
                        start_pos = (base_x, base_y)
                        # 计算槽位中的目标位置
                        end_pos = (SLOT_LEFT + len(slots) * (CARD_WIDTH + 5), SLOT_TOP)

    # 移动卡片
    if moving_card is not None:
        x, y = start_pos
        target_x, target_y = end_pos
        if abs(x - target_x) > step:
            x += step if x < target_x else -step
        else:
            x = target_x
        if abs(y - target_y) > step:
            y += step if y < target_y else -step
        else:
            y = target_y
        start_pos = (x, y)
        if x == target_x and y == target_y:
            slots.append(moving_card)
            moving_card = None

            # 检查是否有三个相同的卡片，若有则消除
            if len(slots) >= 3 and slots[-1] == slots[-2] == slots[-3]:
                del slots[-3:]
                score += 1

            if len(slots) >= SLOT_COLS:
                game_over = True

            if check_victory():
                game_won = True
                game_over = True

    # 绘制界面
    if background_img:
        screen.blit(background_img, (0, 0))
    else:
        screen.fill(BG_COLOR)

    # 绘制卡片堆（叠罗汉效果）
    for row in range(GRID_ROWS):
        for col in range(GRID_COLS):
            stack = grid[row][col]
            if not stack:
                continue
            base_x = GRID_LEFT + col * (CARD_WIDTH + SPACING + GROUP_SPACING)
            base_y = GRID_TOP + row * (CARD_HEIGHT + SPACING)

            # 绘制所有层卡片
            for index, card_type in enumerate(stack):
                offset_y = index * 3  # 每张卡片之间的纵向偏移量，调小为3
                if card_images:
                    screen.blit(card_images[card_type], (base_x, base_y + offset_y))
                else:
                    pygame.draw.rect(screen, COLORS[card_type],
                                     (base_x, base_y + offset_y, CARD_WIDTH, CARD_HEIGHT))

    # 绘制槽位背景
    if slot_bg_img:
        screen.blit(slot_bg_img, (SLOT_LEFT - 10, SLOT_TOP - 10))
    else:
        pygame.draw.rect(screen, (200, 200, 200),
                         (SLOT_LEFT - 5, SLOT_TOP - 5,
                          slot_width + 10, SLOT_HEIGHT + 10),
                         border_radius=10)

    # 绘制槽位中的卡片
    for i, card in enumerate(slots):
        x = SLOT_LEFT + i * (CARD_WIDTH + 5)
        if card_images:
            screen.blit(card_images[card], (x, SLOT_TOP))
        else:
            pygame.draw.rect(screen, COLORS[card], (x, SLOT_TOP, CARD_WIDTH, CARD_HEIGHT))

    # 绘制清除按钮
    pygame.draw.rect(screen, BUTTON_COLOR, (BUTTON_LEFT, BUTTON_TOP, BUTTON_WIDTH, BUTTON_HEIGHT), border_radius=10)
    font = pygame.font.Font(None, 24)
    text = font.render(f"清除 ({button_uses})", True, TEXT_COLOR)
    text_rect = text.get_rect(center=(BUTTON_LEFT + BUTTON_WIDTH // 2, BUTTON_TOP + BUTTON_HEIGHT // 2))
    screen.blit(text, text_rect)

    # 绘制状态信息
    font = pygame.font.Font(None, 36)
    text = font.render(f"Score: {score}", True, (0, 0, 0))
    screen.blit(text, (20, 20))

    # 绘制槽位容量提示
    capacity_text = font.render(f"{len(slots)}/{SLOT_COLS}", True, (100, 100, 100))
    screen.blit(capacity_text, (SCREEN_WIDTH - 60, 20))

    # 绘制正在移动的卡片
    if moving_card is not None:
        if card_images:
            screen.blit(card_images[moving_card], start_pos)
        else:
            pygame.draw.rect(screen, COLORS[moving_card], (start_pos[0], start_pos[1], CARD_WIDTH, CARD_HEIGHT))

    if game_over:
        text = font.render("YOU WIN!" if game_won else "GAME OVER!",
                           True, (0, 255, 0) if game_won else (255, 0, 0))
        screen.blit(text, (SCREEN_WIDTH // 2 - 80, SCREEN_HEIGHT // 2 - 20))

    pygame.display.flip()
    clock.tick(60)

pygame.quit()
